import React from 'react'
import {
  inject,
  observer,
} from 'mobx-react'
import {
  Paper,
  List,
  ListItem,
  Card,
  CardHeader,
  CardActions,
  RaisedButton,
  Snackbar,
} from 'material-ui'
import io from 'socket.io-client'
import './styles.css'
import * as utils from '../../util/utils'

const socket = io('http://127.0.0.1:3302')

@inject(stores => {
  return {
    topicStore: stores.topicStore,
  }
})
@observer
class TopicList extends React.Component {
  constructor() {
    super()
    this.state = {
      hasNewTopic: false
    }
  }

  fetchTopic = () => {
    this.props.topicStore.fetchTopics()
  }

  goToTopic(topic) {
    this.props.history.push(`/detail/${topic.id}`)
  }

  parseTime(num) {
    return utils.parseTime(num)
  }

  openNewTopic = () => {
    this.setState({
      hasNewTopic: true
    })
  }

  getNewTopic = () => {
    console.log('刷新')
    this.setState({
      hasNewTopic: false
    })
  }

  addListenerHasNewTopic = () => {
    socket.on('hasNewTopic', () => {
      console.log('hasNewTopic')
      this.setState({
        hasNewTopic: true
      })
    })
  }

  componentWillMount() {
    this.fetchTopic()
    this.addListenerHasNewTopic()
  }

  render() {
    let topics = this.props.topicStore.topics
    return (
      <Paper>
        <div>
          <RaisedButton
            label="获取新文章"
            onClick={this.openNewTopic}
          />
          <RaisedButton
            label="写新文章"
            href="/create"
          />
        </div>
        <List>
          {
            topics.map((topic, index) => {
              return (
                <ListItem
                  key={index}
                  onClick={() => this.goToTopic(topic)}
                  >
                  <Card>
                    <CardHeader
                      title={topic.title}
                      subtitle={this.parseTime(topic.createTime)}
                      />
                    <CardActions style={{paddingBottom: '0'}}>
                      {
                        topic.tags && topic.tags.length > 0 && topic.tags.map((tag, tagIndex) => {
                          return (
                            <RaisedButton
                              label={tag.title}
                              primary={true}
                              style={{marginBottom: '8px'}}
                              key={tagIndex}
                              />
                          )
                        })
                      }
                    </CardActions>
                  </Card>
                </ListItem>
              )
            })
          }
        </List>
        <Snackbar
          open={this.state.hasNewTopic}
          message="有新的文章"
          action="刷新"
          onActionClick={this.getNewTopic}
        />
      </Paper>
    )
  }
}

export default TopicList
